mui.init();

//初始化单页view
var viewApi = mui('#app').view({
	defaultPage: '#setting'
});

//初始化单页的区域滚动
mui('.mui-scroll-wrapper').scroll();

mui.plusReady(function() {
	var user = JSON.parse(localStorage.getItem('$user'));

	var userAccountArr = document.getElementsByClassName("user-account")
	for(var i = 0; i < userAccountArr.length; i++) {
		userAccountArr[i].innerHTML = user.account;
	}

	initHistoryList()
});

// 加载观看记录
function initHistoryList() {

	var user = JSON.parse(localStorage.getItem('$user'));
	var url = 'http://863.cachenow.cn:9981/client/records/' + user.account;
	mui.ajax(url, {
		dataType: 'json',
		type: 'get',
		timeout: 10000,
		success: function(data) {
			var historyList = document.getElementById('history-list');
			mui.each(data.videoList, function(index, item) {
				var li = document.createElement('li');
				li.className = 'mui-table-view-cell mui-media';
				var a_id = 'history-item' + index;
				li.innerHTML = '<a id="' + a_id + '">\
													<div class= "bgDiv">\
														<img style="max-width: 75px;height: 100px;" class="mui-media-object mui-pull-left" src="http://863.cachenow.cn:8089/' + item.img + '">\
														<img style="margin:30px auto;height: 40px;line-height: 100px;" class="mui-media-object mui-pull-right" src="./images/icon/play.png">\
														<div class="mui-media-body">\
															<span style="font-size: 1.2rem;">' + item.title + '</span>\
															<p class="mui-ellipsis" style="margin-top: 60px;">观看至 ' + parseTime(item.beginTime) + '</p>\
														</div>\
													</div>\
												</a>';
				historyList.appendChild(li);
				openPage(a_id, item.mediaId, item.beginTime);
			});

		},
		error: function(error) {
			console.log("无法获取轮播图数据!");
		}
	});

}

// 将数值类型的time
function parseTime(time) {
	var hour = Math.floor(time / 3600)
	var minute = Math.floor(time % 3600 / 60)
	var second = Math.floor(time % 3600 % 60 / 60)
	if(hour < 10) {
		hour = '0' + hour
	}
	if(minute < 10) {
		minute = '0' + minute
	}
	if(second < 10) {
		second = '0' + second
	}
	return hour + ":" + minute + ":" + second
}

/**
 * 打开点播播放页面
 */
function openPage(id, mediaId, beginTime) {
	var a = document.getElementById(id);
	a.addEventListener('tap', function() {
		plus.plugintest.openVodPage(mediaId, beginTime);
	})
}

setTimeout(function() {
	defaultImg();
	setTimeout(function() {
		initImgPreview();
	}, 300);
}, 500);

// 退出操作
document.getElementById('exit').addEventListener('tap', function() {
	var btnArray = [{
		title: "注销当前账号"
	}, {
		title: "直接关闭应用"
	}];
	plus.nativeUI.actionSheet({
		cancel: "取消",
		buttons: btnArray
	}, function(event) {
		var index = event.index;
		switch(index) {
			case 1:
				//注销账号
				app.setState({});
				/*
				 * 注意：
				 * 1、因本示例应用启动页就是登录页面，因此注册成功后，直接显示登录页即可；
				 * 2、如果真实案例中，启动页不是登录页，则需修改，使用mui.openWindow打开真实的登录页面
				 */
				//plus.webview.getLaunchWebview().show("pop-in");
				//若启动页不是登录页，则需通过如下方式打开登录页
				mui.openWindow({
					url: 'login.html',
					id: 'login',
					show: {
						aniShow: 'pop-in'
					}
				});
				break;
			case 2:
				plus.runtime.quit();
				break;
		}
	});
}, false);

// 检查更新
document.getElementById("update").addEventListener('tap', function() {
	var server = "http://www.dcloud.io/check/update"; //获取升级描述文件服务器地址
	mui.getJSON(server, {
		"appid": plus.runtime.appid,
		"version": plus.runtime.version,
		"imei": plus.device.imei
	}, function(data) {
		if(data.status) {
			plus.ui.confirm(data.note, function(i) {
				if(0 == i) {
					plus.runtime.openURL(data.url);
				}
			}, data.title, ["立即更新", "取　　消"]);
		} else {
			mui.toast('IPTV已是最新版本!')
		}
	});
});

var view = viewApi.view;
(function($) {
	//处理view的后退与webview后退
	var oldBack = $.back;
	$.back = function() {
		if(viewApi.canBack()) { //如果view可以后退，则执行view的后退
			viewApi.back();
		} else { //执行webview后退
			quit();
		}
	};
	//监听页面切换事件方案1,通过view元素监听所有页面切换事件，目前提供pageBeforeShow|pageShow|pageBeforeBack|pageBack四种事件(before事件为动画开始前触发)
	//第一个参数为事件名称，第二个参数为事件回调，其中e.detail.page为当前页面的html对象
	view.addEventListener('pageBeforeShow', function(e) {
		//				console.log(e.detail.page.id + ' beforeShow');
	});
	view.addEventListener('pageShow', function(e) {
		//				console.log(e.detail.page.id + ' show');
	});
	view.addEventListener('pageBeforeBack', function(e) {
		//				console.log(e.detail.page.id + ' beforeBack');
	});
	view.addEventListener('pageBack', function(e) {
		//				console.log(e.detail.page.id + ' back');
	});
})(mui);

// 更换头像
mui(".mui-table-view-cell").on("tap", "#head", function(e) {
	if(mui.os.plus) {
		var a = [{
			title: "拍照"
		}, {
			title: "从手机相册选择"
		}];
		plus.nativeUI.actionSheet({
			title: "修改头像",
			cancel: "取消",
			buttons: a
		}, function(b) {
			switch(b.index) {
				case 0:
					break;
				case 1:
					getImage();
					break;
				case 2:
					galleryImg();
					break;
				default:
					break
			}
		})
	}

});

function getImage() {
	var c = plus.camera.getCamera();
	c.captureImage(function(e) {
		plus.io.resolveLocalFileSystemURL(e, function(entry) {
			var s = entry.toLocalURL() + "?version=" + new Date().getTime();
			console.log(s);
			document.getElementById("head-img").src = s;
			document.getElementById("head-img1").src = s;
			//变更大图预览的src
			//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
			document.querySelector("#__mui-imageview__group .mui-slider-item img").src = s + "?version=" + new Date().getTime();;;
		}, function(e) {
			console.log("读取拍照文件错误：" + e.message);
		});
	}, function(s) {
		console.log("error" + s);
	}, {
		filename: "_doc/head.jpg"
	})
}

function galleryImg() {
	plus.gallery.pick(function(a) {
		plus.io.resolveLocalFileSystemURL(a, function(entry) {
			plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
				root.getFile("head.jpg", {}, function(file) {
					//文件已存在
					file.remove(function() {
						console.log("file remove success");
						entry.copyTo(root, 'head.jpg', function(e) {
								var e = e.fullPath + "?version=" + new Date().getTime();
								document.getElementById("head-img").src = e;
								document.getElementById("head-img1").src = e;
								//变更大图预览的src
								//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
								document.querySelector("#__mui-imageview__group .mui-slider-item img").src = e + "?version=" + new Date().getTime();;
							},
							function(e) {
								console.log('copy image fail:' + e.message);
							});
					}, function() {
						console.log("delete image fail:" + e.message);
					});
				}, function() {
					//文件不存在
					entry.copyTo(root, 'head.jpg', function(e) {
							var path = e.fullPath + "?version=" + new Date().getTime();
							document.getElementById("head-img").src = path;
							document.getElementById("head-img1").src = path;
							//变更大图预览的src
							//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
							document.querySelector("#__mui-imageview__group .mui-slider-item img").src = path;
						},
						function(e) {
							console.log('copy image fail:' + e.message);
						});
				});
			}, function(e) {
				console.log("get _www folder fail");
			})
		}, function(e) {
			console.log("读取拍照文件错误：" + e.message);
		});
	}, function(a) {}, {
		filter: "image"
	})
};

function defaultImg() {
	if(mui.os.plus) {
		plus.io.resolveLocalFileSystemURL("_doc/head.jpg", function(entry) {
			var s = entry.fullPath + "?version=" + new Date().getTime();;
			document.getElementById("head-img").src = s;
			document.getElementById("head-img1").src = s;
		}, function(e) {
			document.getElementById("head-img").src = 'images/iptv_logo.jpg';
			document.getElementById("head-img1").src = 'images/iptv_logo.jpg';
		})
	} else {
		document.getElementById("head-img").src = 'images/iptv_logo.jpg';
		document.getElementById("head-img1").src = 'images/iptv_logo.jpg';
	}

}
document.getElementById("head-img1").addEventListener('tap', function(e) {
	e.stopPropagation();
});

function initImgPreview() {
	var imgs = document.querySelectorAll("img.mui-action-preview");
	imgs = mui.slice.call(imgs);
	if(imgs && imgs.length > 0) {
		var slider = document.createElement("div");
		slider.setAttribute("id", "__mui-imageview__");
		slider.classList.add("mui-slider");
		slider.classList.add("mui-fullscreen");
		slider.style.display = "none";
		slider.addEventListener("tap", function() {
			slider.style.display = "none";
		});
		slider.addEventListener("touchmove", function(event) {
			event.preventDefault();
		})
		var slider_group = document.createElement("div");
		slider_group.setAttribute("id", "__mui-imageview__group");
		slider_group.classList.add("mui-slider-group");
		imgs.forEach(function(value, index, array) {
			//给图片添加点击事件，触发预览显示；
			value.addEventListener('tap', function() {
				slider.style.display = "block";
				_slider.refresh();
				_slider.gotoItem(index, 0);
			})
			var item = document.createElement("div");
			item.classList.add("mui-slider-item");
			var a = document.createElement("a");
			var img = document.createElement("img");
			img.setAttribute("src", value.src);
			a.appendChild(img)
			item.appendChild(a);
			slider_group.appendChild(item);
		});
		slider.appendChild(slider_group);
		document.body.appendChild(slider);
		var _slider = mui(slider).slider();
	}
}

if(mui.os.stream) {
	document.getElementById("check_update").display = "none";
}

// 退出APP
function quit() {
	var backButtonPress = 0;
	mui.back = function(event) {
		backButtonPress++;
		if(backButtonPress > 1) {
			plus.runtime.quit();
		} else {
			plus.nativeUI.toast('再按一次退出应用');
		}
		setTimeout(function() {
			backButtonPress = 0;
		}, 1000);
		return false;
	};
}